package com.car.action.admin;

import java.text.ParseException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Random;

import javax.xml.ws.Action;

import org.apache.commons.compress.utils.Lists;

import com.alibaba.fastjson.JSONArray;
import com.car.common.model.AdminUser;
import com.car.common.model.Area;
import com.car.common.model.Card;
import com.car.common.model.CardDiscuss;
import com.car.common.model.CardHot;
import com.car.common.model.CardImg;
import com.car.common.model.CardLike;
import com.car.common.model.MessageUnreadNum;
import com.car.common.model.NavyUsers;
import com.car.common.model.RemindMessage;
import com.car.common.model.Social;
import com.car.common.model.UserFans;
import com.car.common.model.UserSees;
import com.car.common.model.Users;
import com.car.common.model.UsersInfo;
import com.car.common.model.VipRecord;
import com.car.intercept.AdminInterceptor;
import com.google.common.collect.Maps;
import com.jfinal.aop.Before;
import com.jfinal.core.Controller;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.ehcache.CacheKit;
import com.jfinal.plugin.ehcache.IDataLoader;
import com.utils.CookiesUtil;
import com.utils.DateUtil;
import com.utils.HttpRequestUtil;
import com.utils.JwtToken;
import com.utils.PicUtil;
import com.utils.RongCloudUtil;
import com.utils.StringUtil;
import com.utils.SystemClock;
import com.utils.Toolkit;

public class CardController extends Controller  {
	
	@Before(AdminInterceptor.class)
	public void copy(){
		Card card = Card.dao.findById(getPara("card_id"));
		
		List<CardImg> imgs = CardImg.dao.find("select * from card_img where card_id = " + card.getId());
		String images = "";
		for(CardImg img :imgs) {
			images += img.getImageUrl() + ",";
		}
		if (images.length() > 0) {
			images = images.substring(0, images.length() -1);
		}
		try {
			Db.update("update card set is_forward = 1 where id = " + getPara("card_id"));
			Users users = Users.dao.findById(card.getUserId());
			// "&token="+JwtToken.createToken(200000L+ card.getUserId()
			String params = "images="+images+"&topic_id="+card.getTopicId()+"&content="+card.getContent()+"&sex="+users.getSex()+"&area_id="+users.getAreaId();
			List<CardDiscuss> discussList = CardDiscuss.dao.find("Select u.area_id,u.sex,d.content,d.user_id from card_discuss as d LEFT JOIN users as u on u.id = d.user_id where d.card_id = " + getPara("card_id") +" ORDER BY RAND() ");
//			List<Map<String,Object>> paramList = Lists.newArrayList();
			String discusses = "";
			for(CardDiscuss d :discussList) {
				int is_card_ower = d.getUserId().intValue() == card.getUserId().intValue() ? 1:0;
				discusses += d.get("area_id")+"_" + d.get("sex") + "_" + StringUtil.decode(d.getStr("content"))+"_" + is_card_ower + ",";
			}
			if (discusses.length() > 0) {
				params += "&discusses=" + discusses.substring(0,discusses.length() - 1);
			}
			
			if (!StringUtil.empty(getPara("user_id")) ) {
				params += "&user_id=" + getPara("user_id");
			} else {
				params += "&user_id=0";
			}
			System.out.println("api.aicishi.cn:"+HttpRequestUtil.sendPost("http://api.aicishi.cn/card/copy_card",params));
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		renderText("操作成功!");
	}
	
	
	// TODO 老帖新发  评论 用B类 C类水军
	@Before(AdminInterceptor.class)
	public void repeat(){
		Db.update("update card set delete_time = "+ SystemClock.now()/1000L + " where id = " + getPara("card_id"));
		Card old = Card.dao.findById(getPara("card_id"));
		
		int old_user_id = old.getUserId().intValue();
		
		int new_user_id = 0;
		
		if (!StringUtil.empty(getPara("user_id"))  && !"0".equals(getPara("user_id"))) {
			new_user_id = getParaToInt("user_id");
		} else {
			new_user_id = old_user_id;
		}
		
		Card one = new Card();
		one.setTopicId(old.getTopicId());
		one.setUserId(new_user_id);
		one.setImages(old.getImages());
		one.setCreateTime(SystemClock.now()/1000L);
		one.setTCreateTime(SystemClock.now()/1000L);
    	one.setUpdateTime(SystemClock.now()/1000L);
    	
    	String create_time = getPara("create_time");
		if (!StringUtil.empty(create_time)) {
			try {
				one.setCreateTime(DateUtil.commonDateTimeFormat.parse(create_time).getTime() /1000L);
			} catch (ParseException e) {
			}
		}
    	one.setContent(old.getContent());
		one.setImgCheck(1);
		one.setIsShow(1);
		one.setIsCheck(1);
		int hot_value = 100 + new Random().nextInt(900);
		one.setViews(30 + new Random().nextInt(500));
		one.setHeat(hot_value);
		one.setTHeat(hot_value);
		one.setSortHeat(4);
		if (one.save()) {
			CardHot hot = new CardHot();
			hot.setCardId(one.getId().intValue());
			hot.setHotVal(hot_value);
			hot.setType(2);
			hot.save();
			Db.update("update users set hot_val = hot_val + " + hot_value/20 +" where id = " + old_user_id);
				
			List<CardImg> old_imgs = CardImg.dao.find("select * from card_img where card_id = " + old.getId());
			for(CardImg old_img :old_imgs) {
				CardImg img = new CardImg();
				img.setCardId(one.getId().intValue());
				img.setImageUrl(old_img.getImageUrl());
				img.setCreateTime(SystemClock.now()/1000L);
				img.setUpdateTime(SystemClock.now()/1000L);
				img.setImgCheck(1);
				img.save();
			}
			
			List<CardDiscuss> old_discusses = CardDiscuss.dao.find("select d.type,u.area_id,u.sex,d.content,d.user_id,d.buser_id from card_discuss as d LEFT JOIN users as u on u.id = d.user_id where d.card_id = " + getPara("card_id") +" ORDER BY RAND() ");
			
			for(CardDiscuss old_discuss :old_discusses) {
				// 判断是不是楼主
				CardDiscuss d_one = new CardDiscuss();
				if(old_user_id == old_discuss.getUserId().intValue()) {
					d_one.setUserId(new_user_id);
					d_one.setBuserId(0);
				} else {
					Users d_users = Users.dao.findFirst("select id from users where is_true = 2 and is_true = 3 and sex = " + old_discuss.get("sex") +" and area_id = " + old_discuss.get("area_id") + " order by rand() limit 1 " );
					if (d_users == null) {
						d_users = Users.dao.findFirst("select id from users where is_true > 1 and sex = " + old_discuss.get("sex") +" and area_id = " + old_discuss.get("area_id") + " order by rand() limit 1 " );
					}
					int d_user_id  = d_users.getId().intValue();
//					
					if(old_user_id == old_discuss.getBuserId().intValue()) {
						d_one.setBuserId(new_user_id);
					} else {
						d_one.setBuserId(d_user_id);
					}
					
					d_one.setUserId(d_user_id);	
				}
				d_one.setType(old_discuss.getType());
				d_one.setCardId(one.getId().intValue());
				d_one.setCreateTime(SystemClock.FUTURE_TIME);
				d_one.setUpdateTime(SystemClock.FUTURE_TIME);
				d_one.setContent(old_discuss.getContent());
				d_one.save();
			}
		}
		renderText("操作成功!");
	}
	
	
	// 点赞页面
	@Before(AdminInterceptor.class)
    public void detail(){
    	Card card = Card.dao.findById(getPara("id"));
    	if(card == null) {
    		renderText("已删除");
    		return;
    	}
    	ArrayList<Social> socialList = CacheKit.get("constant", "sociallist", new IDataLoader(){
		       public Object load() {
		           return Social.dao.getAll();
		}});
	 	ArrayList<Area> areaList = CacheKit.get("constant", "arealist", new IDataLoader(){
			       public Object load() {
			           return Area.dao.getIProvince();
			}});
	 	setAttr("social_list", socialList);
	 	setAttr("area_list", areaList);

	 	if (card != null ){
	 		card.setContent(StringUtil.decode(card.getContent()));
	 	}
	 	Users users = Users.dao.findById(card.getUserId());
	 	if (users != null ){
	 		users.setUserHeader(users.getUserHeader() + PicUtil.QINIU_CUT_ADMIN);
	 		users.setNickName(StringUtil.decode(users.getNickName()));
	 	}
        List<CardDiscuss> discussList = CardDiscuss.dao.find("select a.id,a.type,a.content,a.buser_id,a.discuss_id,a.user_id,a.create_time, FROM_UNIXTIME(a.create_time,'%Y-%m-%d %H:%i') as  create_time_string,u.nick_name,u.user_header from card_discuss as a LEFT JOIN users as u on u.id = a .user_id where a.card_id = " + getPara("id") + " and ((a.type < 2 ) or (a.type = 2 and a.discuss_id = 0 )) order by a.id desc");
        List<Map<String,Object>> discuss_list = Lists.newArrayList();
        for(CardDiscuss one :discussList ) {
//        	one.setContent(StringUtil.decode(one.getContent()));
        	Map<String,Object> temp = Maps.newHashMap();
        	temp.put("id", one.get("id"));
        	temp.put("type", one.get("type"));
        	if (one.getInt("discuss_id") != 0) {
        		temp.put("content", StringUtil.decode(one.getContent()));
        	} else {
        		if (one.getUserId().intValue() == one.getBuserId().intValue()) {
        			temp.put("content", StringUtil.decode(one.getContent()));
        		} else {
        			Users users_temp = Users.dao.findById(one.getBuserId());
            		if (users_temp != null) {
            			temp.put("content", "回复 "+ StringUtil.decode(users_temp.getNickName()) + ": "+ StringUtil.decode(one.getContent()));
            		} else {
            			temp.put("content", StringUtil.decode(one.getContent()));
            		}
        		}
        		
        	}
        	
        	temp.put("create_time_string", one.get("create_time_string"));
        	temp.put("user_id", one.get("user_id"));
        	temp.put("nick_name", StringUtil.decode(one.get("nick_name")));
        	temp.put("user_header", PicUtil.QINIU_DIR + one.getStr("user_header"));
        	temp.put("create_time", one.get("create_time"));
        	discuss_list.add(temp);
        }
        List<CardImg> imgList = CardImg.dao.find("select * from card_img where card_id = " + getPara("id") );
        
        setAttr("one", card);
        setAttr("create_time", DateUtil.commonDateTimeFormat.format(new Date(card.getCreateTime()*1000L)));
        setAttr("users", users);
        setAttr("discuss_list", discuss_list);
        setAttr("img_list", imgList);
        render("detail.html");
    }

	public void answer_list() {
		List<CardDiscuss> answerList = CardDiscuss.dao.find("select a.id,a.type,a.create_time,a.user_id,a.content,a.card_id,b.nick_name,b.user_header  from card_discuss as a left join users b on b.id = a.user_id where a.type = 2 and a.discuss_id = " +  getPara("discuss_id") + " order by a.id desc" );
		ArrayList<Map<String,Object>> result1 = Lists.newArrayList();
		for(CardDiscuss one1 : answerList) {
			Map<String,Object> temp1 = Maps.newHashMap();
			temp1.put("id", one1.get("id"));
			temp1.put("type", one1.get("type"));
			temp1.put("content",       StringUtil.decode(one1.getStr("content")));
			temp1.put("user_id",       one1.get("user_id"));
			temp1.put("create_time",   DateUtil.cul(one1.getCreateTime()));
			temp1.put("nick_name",     StringUtil.decode(one1.getStr("nick_name")));
			temp1.put("user_header",   PicUtil.QINIU_DIR + one1.get("user_header"));
			temp1.put("create_time",   one1.get("create_time"));
			result1.add(temp1);
		}
		renderJson(result1);
//		temp.put("answer_list",           result1);
	}
		
	// 点赞页面
	@Before(AdminInterceptor.class)
    public void like(){
    	Card card =  Card.dao.findById(getPara("id"));
        ArrayList<Area> areaList = CacheKit.get("constant", "arealist", new IDataLoader(){
		       public Object load() {
		           return Area.dao.getIProvince();
		}});
        setAttr("one", card);
        setAttr("area_list", areaList);
        
        render("like.html");
    }
	
	// 评论页面
	@Before(AdminInterceptor.class)
    public void discuss() {
    	Card card =  Card.dao.findById(getPara("id"));
		setAttr("one", card);
		ArrayList<Area> areaList = CacheKit.get("constant", "arealist", new IDataLoader(){
		       public Object load() {
		           return Area.dao.getIProvince();
		       }
		});
        setAttr("area_list", areaList);
        render("discuss.html");
    }
	
	
	/**
	 * TODO 代替AB点  ，切换
	 * @param user_id
	 */
	public void giveABPoint(int user_id) {
		
		Db.update("update users set login_status = 0,logout_time = "+ (SystemClock.now()/1000L + 5 * 6 * 60L + new Random().nextInt(5)* 30 *60L ) +"  where id = " + user_id);
		/*
		Users users = Users.dao.findById(user_id);
		if (users.getIsTrue()  == 2) {
			UsersInfo users_info = UsersInfo.dao.findFirst("select * from users_info where user_id = " + user_id);
			if (users_info != null) {
				String lat = users_info.getLat();
				String lng = users_info.getLng();
				if (StringUtil.empty(lat) || StringUtil.empty(lng)) {
					String gps =  Toolkit.getRandGPS(new Double(114.170434), new Double(30.552575), 650.0);
					String new_lat = gps.split(",")[0];
					String new_lng = gps.split(",")[1];
					// 没位置设置A点
					Db.update("update users_info set lat = " + new_lat +",lng =" + new_lng +" where user_id= " + user_id);
					// 水军设置B点
					String gps2 =  Toolkit.getRandGPS(new Double(new_lat), new Double(new_lng), 2000000.0);
					String lat_A = gps2.split(",")[0];
					String lng_A = gps2.split(",")[1];
					Db.update("update users_info set lat_A = " + lat_A +",lng_A =" + lng_A +" where user_id= " + user_id);
				}
			}
		}
		*/
	}
	
	
	public void fastGiveDiscuss(){
		getResponse().setHeader("Access-Control-Allow-Origin", "*");
		int id = getParaToInt("id");
		CardDiscuss discuss =  CardDiscuss.dao.findById(id);
		if(discuss != null) {
			CardDiscuss one = new CardDiscuss();
			one.setContent(StringUtil.encode(getPara("content")) );
			one.setCardId(discuss.getCardId());
			if(discuss.getUserId().intValue() == discuss.getBuserId().intValue()) {
				Card card = Card.dao.findById(discuss.getCardId());
				one.setUserId(card.getUserId());
				one.setBuserId(discuss.getUserId());
			} else {
				one.setUserId(discuss.getBuserId());
				one.setBuserId(discuss.getUserId());
			}
			one.setCreateTime(SystemClock.now()/1000L);
        	one.setUpdateTime(SystemClock.now()/1000L);
        	one.set("is_discuss",1);
        	one.set("type", 2);
			if (one.save()) {
				Db.update("update card_discuss set is_discuss = 1 where id = " + discuss.getId());
				giveABPoint(discuss.getBuserId());
				Db.update("update card set discuss = discuss + 1,discuss_cnt = discuss_cnt + 1,views = views + 50,t_views = t_views + 50 where id = " + discuss.getCardId());
			}
		}
		renderText("操作成功!");
	}
    
	/**
	  *   增加评论
	 * @param id
	 * @param content
	 * @param area  
	 */
	public void giveDiscuss(){
		int type = getParaToInt("type");
		String content = getPara("content");
		String area = getPara("area");
		Card card = Card.dao.findById(getPara("id"));
		
		discuss(card,content,type,getPara("buser_id"),area);
		renderText("操作成功!");
 	}

	
	public void save_content(){
		Card card = Card.dao.findById(getPara("card_id"));
		if (card != null) {
			card.setContent(getPara("content"));
			card.update();
		}
		renderText("操作成功!");
	}
	
	/**
	 * 
	 * @param card
	 * @param content
	 * @param type   0 立即发送  1 进入评论仓库
	 */
	public void discuss(Card card,String content,int type,String buser_id,String area) {
		// 楼主回复
		if ("-1".equals(area)) {
			CardDiscuss one = new CardDiscuss();
			one.setContent(StringUtil.encode(content) );
			one.setCardId(card.getId().intValue());
			one.setUserId(card.getUserId());
			if (StringUtil.empty(buser_id)) {
				one.setBuserId(card.getUserId());
			} else {
				int buser_id_int = Integer.valueOf(buser_id);
				if (buser_id_int > 0) {
					one.setBuserId(buser_id_int);
					MessageUnreadNum.dao.addNum(MessageUnreadNum.MESSAGE_UNREAD_TYPE_DISCUSS, buser_id_int);
				}
			}
			if (type == 0) {
				one.setCreateTime(SystemClock.now()/1000L);
	        	one.setUpdateTime(SystemClock.now()/1000L);
	        	Db.update("update card set discuss = discuss + 1,discuss_cnt = discuss_cnt + 1,views = views + 50,t_views = t_views + 50 where id = " + card.getId());
			} else {
				one.setCreateTime(SystemClock.FUTURE_TIME);
	        	one.setUpdateTime(SystemClock.FUTURE_TIME);
			}
			
        	one.set("type", 1);
			if (one.save()) {
				giveABPoint(card.getUserId());
			}
		// 随机男
		}else if (StringUtil.empty(area) || "0".equals(area)) {
			Users users = Users.dao.findFirst("select u.id from users as u left join users_info as i on u.id = i.user_id where u.is_true = 3 and u.sex = 1 and i.lat is not null order by rand() LIMIT 1 ");
			CardDiscuss one = new CardDiscuss();
			one.setContent(StringUtil.encode(content) );
			one.setCardId(card.getId().intValue());
			int userid = users.getId().intValue();
			one.setUserId(userid);
			if (StringUtil.empty(buser_id)) {
				one.setBuserId(userid);
			} else {
				int buser_id_int = Integer.valueOf(buser_id);
				if (buser_id_int > 0) {
					one.setBuserId(buser_id_int);
					MessageUnreadNum.dao.addNum(MessageUnreadNum.MESSAGE_UNREAD_TYPE_DISCUSS, buser_id_int);
				}
			}
			if (type == 0) {
				one.setCreateTime(SystemClock.now()/1000L);
	        	one.setUpdateTime(SystemClock.now()/1000L);
	        	Db.update("update card set discuss = discuss + 1, discuss_cnt = discuss_cnt + 1,views = views + 50,t_views = t_views + 50 where id = " + card.getId());
			} else {
				one.setCreateTime(SystemClock.FUTURE_TIME);
	        	one.setUpdateTime(SystemClock.FUTURE_TIME);
			}
			
        	one.set("type", 1);
			if (one.save()) {
				giveABPoint(userid);
				MessageUnreadNum.dao.addNum(MessageUnreadNum.MESSAGE_UNREAD_TYPE_DISCUSS, card.getUserId());
			}
		}else if ("1".equals(area)) {
			Users users = Users.dao.findFirst("select u.id from users as u left join users_info as i on u.id = i.user_id where u.is_true = 3 and u.sex = 2 and i.lat is not null order by rand() LIMIT 1");
			CardDiscuss one = new CardDiscuss();
			one.setContent(StringUtil.encode(content) );
			one.setCardId(card.getId().intValue());
			int userid = users.getId().intValue();
			one.setUserId(userid);
			if (StringUtil.empty(buser_id)) {
				one.setBuserId(userid);
			} else {
				int buser_id_int = Integer.valueOf(buser_id);
				if (buser_id_int > 0) {
					one.setBuserId(buser_id_int);
					MessageUnreadNum.dao.addNum(MessageUnreadNum.MESSAGE_UNREAD_TYPE_DISCUSS, buser_id_int);
				}
			}
			if (type == 0) {
				one.setCreateTime(SystemClock.now()/1000L);
	        	one.setUpdateTime(SystemClock.now()/1000L);
	        	Db.update("update card set discuss = discuss + 1,discuss_cnt = discuss_cnt + 1,views = views + 50,t_views = t_views + 50 where id = " + card.getId());
			} else {
				one.setCreateTime(SystemClock.FUTURE_TIME);
	        	one.setUpdateTime(SystemClock.FUTURE_TIME);
			}
			
        	one.set("type", 1);
			if (one.save()) {
				giveABPoint(userid);
				MessageUnreadNum.dao.addNum(MessageUnreadNum.MESSAGE_UNREAD_TYPE_DISCUSS, card.getUserId());
			}
		}else {
			AdminUser adminUser = getSessionAttr(LoginController.ADMIN_SESSION_KEY);
			if (adminUser != null) {
				NavyUsers users = NavyUsers.dao.findFirst("select a.* from navy_users as a  left join users as u on u.id = a.user_id  where u.user_header is not null and u.area_id = " + getPara("area") +" and a.admin_user_id = " + adminUser.getId() +" order by  RAND()  limit 1 " );
				if (users != null ) {
					CardDiscuss one = new CardDiscuss();
					one.setContent(StringUtil.encode(getPara("content")) );
					one.setCardId(card.getId().intValue());
					int userid = users.getUserId();
					one.setUserId(userid);
					one.setBuserId(userid);
					if (type == 0) {
						one.setCreateTime(SystemClock.now()/1000L);
			        	one.setUpdateTime(SystemClock.now()/1000L);
			        	Db.update("update card set  discuss = discuss + 1,discuss_cnt = discuss_cnt + 1,views = views + 50,t_views = t_views + 50 where id = " + card.getId());
					} else {
						one.setCreateTime(SystemClock.FUTURE_TIME);
			        	one.setUpdateTime(SystemClock.FUTURE_TIME);
					}
					
		        	one.set("type", 1);
					if (one.save()) {
						giveABPoint(userid);
						
						//增加未读消息数
						MessageUnreadNum.dao.addNum(MessageUnreadNum.MESSAGE_UNREAD_TYPE_DISCUSS, card.getUserId());
					}
				}

			}
		}
	}

	// 点赞
	@Before(AdminInterceptor.class)
    public void giveLike(){
    	int id = getParaToInt("id");
		AdminUser adminUser = getSessionAttr(LoginController.ADMIN_SESSION_KEY);
		String sql = "select a.* from navy_users as a left join users as u on u.id = a.user_id where u.user_header is not null and  a.admin_user_id = " + adminUser.getId(); 
		if (getPara("area") != null && !getPara("area").equals("0")) {
			sql = sql + " and u.area_id = " + getPara("area");
		}
		sql = sql +" order by  RAND()  limit  " + getPara("num");
		List<NavyUsers> usersList = NavyUsers.dao.find(sql);
		if (usersList == null || usersList.size() == 0 ) {
			render("操作失败,此地区没有第三方登录用户.");
		} else {
			Card card = Card.dao.findById(id);
			for(int i = 0 ; i < usersList.size(); i++) {
				NavyUsers u = usersList.get(i);
				CardLike one = CardLike.dao.findFirst("select * from card_like where card_id = " + id +" and user_id = " + u.getUserId() +" order by id desc limit 1" );
				if (one == null) {
					one = new CardLike();
					one.setCardId(id);
					one.set("status", 1);
					one.set("user_id", u.getUserId());
					one.set("is_auth", 2);
					one.setCreateTime(SystemClock.now()/1000L);
		        	one.setUpdateTime(SystemClock.now()/1000L);
					if (one.save()) {
						giveABPoint(u.getUserId());
						Db.update("update users set user_money = user_money + 6 where id = " +  u.getId());
						Db.update("update card set sort_heat = sort_heat + 6,fabulous = fabulous + 1,views = views + 10,t_views = t_views + 10 where id = " +  id);
						MessageUnreadNum.dao.addNum(MessageUnreadNum.MESSAGE_UNREAD_TYPE_LIKE, card.getUserId());
					}
				}
	        } 
	    	renderText("操作成功!");
		}
	}
	
	
	// 关注
	@Before(AdminInterceptor.class)
	public void giveFollow(){
	    Card card = Card.dao.findById(getPara("id"));
	    String sql = "SELECT t1.id FROM `users` AS t1 JOIN (SELECT ROUND(RAND() * (SELECT MAX(id) FROM `users`)) AS id) AS t2 WHERE t1.id >= t2.id and is_true > 1 and sex = 1 ORDER BY t1.id ASC LIMIT "+ getPara("num");
	    List<Users> users = Users.dao.find(sql);
	    for(Users u : users) {
	    	Long user_id = u.getId(); 
	    	int target_user_id = card.getUserId();
	    	
	    	UserSees one1 = new UserSees();
 			one1.setUserId(user_id.intValue());
 			one1.setTargetUserId(target_user_id);
 			one1.setCreateTime(SystemClock.now()/1000L - 1 * 60);
 			one1.setUpdateTime(SystemClock.now()/1000L);
 			if (one1.save()) {
 				new CardController().giveABPoint(user_id.intValue());
 				MessageUnreadNum.dao.addNum(MessageUnreadNum.MESSAGE_UNREAD_TYPE_SEE, target_user_id);
 			}
	    	//判断是否关注
			UserFans one = UserFans.dao.findFirst("select id , user_id from user_fans where user_id = " + user_id+ " and target_user_id = " + target_user_id +" and delete_time is null ");
			if (one == null) {
				one = new UserFans();
				one.setUserId(user_id.intValue());
				one.setTargetUserId(target_user_id);
				one.setIsAuth(1);
				one.setStatus(1);
				one.setCreateTime(SystemClock.now()/1000L);
				one.setUpdateTime(SystemClock.now()/1000L);
				if (one.save()) {
					giveABPoint(user_id.intValue());
					MessageUnreadNum.dao.addNum(MessageUnreadNum.MESSAGE_UNREAD_TYPE_FAN, target_user_id);
				}	
			} 
	    }
	    renderText("操作成功!");
	}
	
	// 关注
	@Before(AdminInterceptor.class)
	public void giveFollow2(){
	    String sql = "SELECT t1.id FROM `users` AS t1 JOIN (SELECT ROUND(RAND() * (SELECT MAX(id) FROM `users`)) AS id) AS t2 WHERE t1.id >= t2.id and is_true > 1 and sex = 1 ORDER BY t1.id ASC LIMIT " + getPara("num");
	    List<Users> users = Users.dao.find(sql);
	    for(Users u : users) {
	    	Long user_id = u.getId(); 
	    	int target_user_id = getParaToInt("user_id");
	    	
	    	UserSees one1 = new UserSees();
 			one1.setUserId(user_id.intValue());
 			one1.setTargetUserId(target_user_id);
 			one1.setCreateTime(SystemClock.now()/1000L - 1 * 60);
 			one1.setUpdateTime(SystemClock.now()/1000L);
 			if (one1.save()) {
 				new CardController().giveABPoint(user_id.intValue());
 				MessageUnreadNum.dao.addNum(MessageUnreadNum.MESSAGE_UNREAD_TYPE_SEE, target_user_id);
 			}
	    	//判断是否关注
			UserFans one = UserFans.dao.findFirst("select id , user_id from user_fans where user_id = " + user_id+ " and target_user_id = " + target_user_id +" and delete_time is null ");
			if (one == null) {
				one = new UserFans();
				one.setUserId(user_id.intValue());
				one.setTargetUserId(target_user_id);
				one.setIsAuth(1);
				one.setStatus(1);
				one.setCreateTime(SystemClock.now()/1000L);
				one.setUpdateTime(SystemClock.now()/1000L);
				if (one.save()) {
					giveABPoint(user_id.intValue());
					MessageUnreadNum.dao.addNum(MessageUnreadNum.MESSAGE_UNREAD_TYPE_FAN, target_user_id);
				}	
			} 
	    }
	    renderText("操作成功!");
	}
	 
    //列表
    @Before(AdminInterceptor.class)
    public void index(){
    	/*
    	List<CardDiscuss> discussList = CardDiscuss.dao.find("select d.* from card_discuss as d LEFT JOIN  card as c on d.card_id = c.id where c.id is NULL ");
        for(CardDiscuss one :discussList) {
       	   Db.delete("delete from card_discuss where id =" + one.getId());
        }
        Db.delete("delete from user_sees where user_id = 0 ");
          
        Db.delete("DELETE l FROM card_like AS l LEFT JOIN users AS u ON u.id = l.user_id WHERE u.is_true > 1 AND (u.user_header IS NULL or LENGTH(u.user_header) =0)");
          
        Db.delete("DELETE l FROM user_sees AS l LEFT JOIN users AS u ON u.id = l.user_id WHERE u.is_true > 1 AND (u.user_header IS NULL or LENGTH(u.user_header) =0)");
          
        Db.delete("DELETE l FROM card_discuss AS l LEFT JOIN users AS u ON u.id = l.user_id WHERE u.is_true > 1 AND (u.user_header IS NULL or LENGTH(u.user_header) =0)");
        
        Db.delete("update card set is_show = 2 where is_show is null ");
         */
    	ArrayList<Social> socialList = CacheKit.get("constant", "sociallist", new IDataLoader(){
		       public Object load() {
		           return Social.dao.getAll();
		}});
    	
    	ArrayList<Area> areaList = CacheKit.get("constant", "arealist", new IDataLoader(){
		       public Object load() {
		           return Area.dao.getIProvince();
		}});
    	setAttr("social_list", socialList);
    	setAttr("area_list", areaList);
    	
    	String sql = "select a.* ,a.is_show ,u.nick_name,u.user_mobile,u.is_gray,u.id as user_id,s.title as social_title,u.vip_end_time,ae.name as area_name,u.sex,u.is_true,CASE u.sex  WHEN '1' THEN '男' WHEN '2' THEN '女' WHEN '3' THEN 'CD' WHEN '4' THEN 'FtM' WHEN '5' THEN 'MtF'  ELSE '其他' END as sex_name,case u.is_true when '2' then 'B类' when '3' then 'C类'  when '4' then 'D类' else 'A类' end as is_true_name ,IFNULL(a.delete_time, 0) as del_time";
    	sql += ", FROM_UNIXTIME(a.create_time,'%Y-%m-%d %H:%i') as create_time_string , FROM_UNIXTIME(u.vip_end_time,'%Y-%m-%d') as vip_end_time_string  ";
    	String andSql = " from card as a left join users u on u.id = a.user_id left join social s on  s.id = a.tags_id left join area ae on ae.code = u.area_id where a.is_private = 0 and a.create_time != 1893427200 " ;
    	
    	if(!StringUtil.empty(getPara("alt_tj"))) {
        	andSql += " and a.alt_tj = " + getPara("alt_tj");
        }
    	if(!StringUtil.empty(getPara("img"))) {
    		int img = getParaToInt("img");
    		if (img == 1) {
    			andSql += " and LENGTH(a.images) > 0 ";
    		} else if (img == 2) {
    			andSql += " and (a.images is null or LENGTH(a.images) = 0 ) ";
    		} else if (img == 3) {
    			// 本周最热
    			andSql += " and a.create_time > " + (SystemClock.now()/1000L - 7*24*3600L ) ;
    		}
        }
        if(!StringUtil.empty(getPara("is_show"))) {
        	andSql += " and a.is_show = " + getPara("is_show");
        }
        if(!StringUtil.empty(getPara("is_top"))) {
        	
        	if ("3".equals(getPara("is_top"))) {
        		andSql += " and u.is_true > 1 and a.delete_time is null ";
        	}else if ("4".equals(getPara("is_top"))) {
        		andSql += " and u.is_true > 1 and a.is_forward = 0 ";
        	}  
        	else {
        		andSql += " and a.is_top = " + getPara("is_top");
        	}
        	/**
        	 // 是否老帖新发
            if(!StringUtil.empty(getPara("is_forward"))) {
            	
            }
            
            // 是否移动爱此时
            if(!StringUtil.empty(getPara("is_copy"))) {
            	
            }
            **/
        }
        if(!StringUtil.empty(getPara("is_check"))) {
        	andSql += " and a.is_check = " + getPara("is_check");
        }
        if(!StringUtil.empty(getPara("user_mobile"))) {
        	String  user_mobile = getPara("user_mobile");
        	if (user_mobile.length() == 11) {
        		andSql += " and u.user_mobile = " + user_mobile;
        	} else {
        		if (user_mobile.length() > 4) {
        			andSql += " and u.user_mobile like '" + user_mobile +"%'";
        		}
        	}
        }
        if(!StringUtil.empty(getPara("user_id"))) {
        	andSql += " and u.id = " + getPara("user_id");
        }
        if(!StringUtil.empty(getPara("social"))) {
        	andSql += " and a.tags_id = " + getPara("social");
        }
        if(!StringUtil.empty(getPara("nick_name"))) {
        	andSql += " and ( u.nick_name like '%" + StringUtil.encode(getPara("nick_name")).replace("%", "\\%")  +"%' or u.nick_name like '%" + getPara("nick_name") + "%') ";
        }
        
        if(!StringUtil.empty(getPara("content"))) {
        	andSql += " and ( a.content like '%" + StringUtil.encode(getPara("content")).replace("%", "\\%")  +"%' or a.content like  '%" + getPara("content")+ "%') ";
        }
        if(!StringUtil.empty(getPara("card_id"))) {
        	andSql += " and a.id = " + getPara("card_id");
        }
        
        if(!StringUtil.empty(getPara("sex"))) {
        	andSql += " and u.sex = " + getPara("sex");
        }
        if(!StringUtil.empty(getPara("area"))) {
        	andSql += " and ae.code = " + getPara("area");
        } else {
        	if(!StringUtil.empty(getPara("person"))) {
        		if (!"100".equalsIgnoreCase(getPara("person"))) {
        			andSql += StringUtil.getSQLForPerson(getPara("person"));
        			ArrayList<Area> areaList2 = CacheKit.get("constant", "arealist_"+ getPara("person"), new IDataLoader(){
     			       public Object load() {
	     			           return Area.dao.getIProvince(getPara("person"));
	     			}});
	     	 		setAttr("area_list", areaList2);
        		}
        	}
        }
        if(!StringUtil.empty(getPara("is_true"))) {
        	int is_true = getParaToInt("is_true");
        	if (is_true < 100 ) {
        		andSql += " and u.is_true = " + getPara("is_true");
        	} else {
        		andSql += " and u.is_true = 1 and is_gray = 1 ";
        		
        	}
        }
       
        if(!StringUtil.empty(getPara("pre"))) {
        	andSql += " and a.create_time > " + SystemClock.now()/1000L ;
        	if("3".equalsIgnoreCase(getPara("img"))) {
        		andSql += " order by a.heat desc,u.sex desc,u.vip_end_time desc ";
        	} else if("4".equalsIgnoreCase(getPara("img"))) {
        		andSql += " order by a.heat desc ";
        	} else if("5".equalsIgnoreCase(getPara("img"))) {
        		andSql += " order by a.discuss desc ";
        	} else if("6".equalsIgnoreCase(getPara("img"))) {
        		andSql += " and a.delete_time is null order by a.create_time asc ";
        	} else if("7".equalsIgnoreCase(getPara("img"))) {
        		andSql += " and a.is_forward = 0 order by a.create_time asc ";
        	} else {
        		andSql += " order by a.create_time asc ";
        	}
        } else {
        	andSql += " and a.create_time < " + SystemClock.now()/1000L ;
        	if("3".equalsIgnoreCase(getPara("img"))) {
        		andSql += " order by a.heat desc,u.sex desc,u.vip_end_time desc ";
        	} else if("4".equalsIgnoreCase(getPara("img"))) {
        		andSql += " order by a.heat desc ";
        	} else if("5".equalsIgnoreCase(getPara("img"))) {
        		andSql += " order by a.discuss desc ";
        	}  else if("6".equalsIgnoreCase(getPara("img"))) {
        		andSql += " and a.delete_time is null order by a.create_time asc ";
        	} else if("7".equalsIgnoreCase(getPara("img"))) {
        		andSql += " and a.is_forward = 0 order by a.create_time asc ";
        	} else {
        		andSql += " order by a.create_time desc ";
        	}
        }
        int page = 1;
        if(!StringUtil.empty(getPara("page"))) {
        	page = getParaToInt("page");
        } 
        System.out.println(sql + andSql);
        Page<Card> cardPage = Card.dao.paginate(page, 15, sql,andSql);
        for(Card c : cardPage.getList()) {
        	c.set("content", StringUtil.decode(c.getStr("content")));
        }
        setAttr("page", cardPage);
        setAttr("alt_tj", getPara("alt_tj"));
        setAttr("is_show", getPara("is_show"));
        setAttr("is_top", getPara("is_top"));
        setAttr("user_mobile", getPara("user_mobile"));
        setAttr("user_id", getPara("user_id"));
        setAttr("social", getPara("social"));
        setAttr("nick_name", getPara("nick_name"));
        setAttr("card_id", getPara("card_id"));
        setAttr("sex", getPara("sex"));
        setAttr("area", getPara("area"));
        setAttr("is_true", getPara("is_true"));
        setAttr("pre", getPara("pre"));
        setAttr("gps", getPara("gps"));
        setAttr("content", getPara("content"));
        setAttr("img", getPara("img"));
        setAttr("now", SystemClock.now()/1000);
        setAttr("is_forward", getPara("is_forward"));
        setAttr("is_copy", getPara("is_copy"));
        
        
        String person = getPara("person");
        if(StringUtil.empty(person)) {
        	 person = CookiesUtil.getName(getRequest(), "person");
        } else {
        	if ("100".equals(person)) {
        		CookiesUtil.add(getResponse(), "person", "0");
        	} else {
        		CookiesUtil.add(getResponse(), "person", person);
        	}
        	
        }
        setAttr("person", person);
        render("index.html");
   }
    
    //删除 帖子
    public void del(){
    	int id = getParaToInt("id");
    	Db.delete("delete from card_collect where card_id = " + id);
    	Db.delete("delete from card_discuss where card_id = " + id);
    	Db.delete("delete from card_hot where card_id = " + id);
    	List<CardImg> cardImgList = CardImg.dao.find("select * from card_img where card_id = " + id);
    	/*
    	if (cardImgList != null) {
    		PicUtil tool = new PicUtil();
    		for(CardImg img : cardImgList){
    			tool.delete(img.getImageUrl());
    		}
    	}
    	*/
    	Db.delete("delete from card_img where card_id = " + id);
    	Db.delete("delete from card_like where card_id = " + id);
    	Db.delete("delete from card_see where card_id = " + id);
    	Db.delete("delete from card_topic where card_id = " + id);
    	//Db.delete("delete from card_user where card_id = " + id);
    	Db.delete("delete from card where id = " + id);
    	
    	Db.delete("delete from image_qpulp where type =1 and replace_id = " + id);
    	
        renderText("操作成功!");
    }
    
    //发帖
    public void add(){
    	render("add.html");
    }
    //是否推荐
    public void alt(){
    	Db.update("UPDATE card SET alt_tj = ( CASE `alt_tj` WHEN 1 THEN 2   WHEN 2 THEN 1 END ) where id =" +getPara("id"));
        renderText("操作成功!");
    }
    
    //是否展示
    public void show(){
    	int views = 1 + new Random().nextInt(10);
    	Db.update("UPDATE card SET views = views + " + views + " ,is_show = ( CASE `is_show` WHEN 1 THEN 2   WHEN 2 THEN 1 END ) where id =" +getPara("id"));
        renderText("操作成功!");
    }
	
    //是否审核
    public void check(){
    	int views = 5 + new Random().nextInt(40);
    	long create_time = SystemClock.now()/1000L;
    	Db.update("UPDATE card SET t_create_time = "+create_time+"  , views = views + " + views + " ,is_check = ( CASE `is_check` WHEN 0 THEN 1 WHEN 1 THEN 2  WHEN 2 THEN 1 END ) where id =" +getPara("id"));
        renderText("操作成功!");
    }
	
    //是否置顶
    public void top(){
    	Db.update("UPDATE card SET is_top = ( CASE `is_top`  WHEN 1 THEN 2   WHEN 2 THEN 1 END ) where id =" +getPara("id"));
        renderText("操作成功!");
    }
    
    //是否审核
    public void up(){
    	long create_time = SystemClock.now()/1000L;
    	Db.update("UPDATE card SET t_create_time = "+create_time+",is_top = 2  where id =" +getPara("id"));
        renderText("操作成功!");
    }
    
    public void down(){
    	Db.update("UPDATE card SET t_create_time = create_time,is_top = 1  where id =" +getPara("id"));
        renderText("操作成功!");
    }
    
    public void replaceImg() {
    	String str = getPara("str");
    	String[] img = str.split(",");
    	for(String s :img ) {
    		String[] data = s.split("-");
    		String id = data[0];
    		String image_url = data[1];
    		Db.update("update card_img set image_url = '"+ image_url +"' where id = " + id);
    	}
    	updateCardImg(getPara("card_id"));
    	renderText("操作成功!");
    }
    
    
    public void addImg() {
    	CardImg img = new CardImg();
		img.setCardId(getParaToInt("card_id"));
		img.setImageUrl(getPara("url"));
		img.setCreateTime(SystemClock.now()/1000L);
		img.setUpdateTime(SystemClock.now()/1000L);
		img.setImgCheck(1);
		img.save();
		updateCardImg(getPara("card_id"));
    	renderText(String.valueOf(img.getId()));
    }
    
    public void deleteImg() {
    	Db.delete("delete from card_img where id = " + getPara("card_id"));
    	updateCardImg(getPara("card_id"));
    	renderText("操作成功!");
    }
    
    private void updateCardImg(String card_id) {
    	List<CardImg> imgs = CardImg.dao.find("select image_url from card_img where  img_check = 1 and card_id =  " + card_id);
    	if (imgs != null && imgs.size() > 0) {
    		String image_url = "";
    		for (CardImg img : imgs) {
    			image_url += img.getImageUrl() + ",";
			}
    		if (image_url.length() >0) {
    			image_url = image_url.substring(0, image_url.length() -1);
    		}
    		Db.update("update card set images = '" +image_url+"' where id = " + card_id);
    	}
    }
    
    
    public void discuss_cnt_json() {
    	getResponse().setHeader("Access-Control-Allow-Origin", "*");
    	String sql = "select count(a.id) as cnt ";
 		String andSql = " from card_discuss as a left join card as c on c.id = a.card_id left join users as card_users on card_users.id = c.user_id left join users u on u.id = a.user_id left join users as ta on a.buser_id = ta.id left join area ae on ae.code = u.area_id where a.is_discuss = 0 and a.card_id > 0 and a.create_time < "+ SystemClock.now()/1000L ;
    	andSql += " and u.is_true >1 and ( ( a.type= 1 and card_users.is_true > 1 ) or (ta.is_true > 1 and  a.type= 2 and a.buser_id != a.user_id) )" ;
    	
    	CardDiscuss cntDiscuss = CardDiscuss.dao.findFirst(sql +andSql);
    	renderJson(cntDiscuss.getLong("cnt"));
    }
    
    public void discuss_last_json() {
    	getResponse().setHeader("Access-Control-Allow-Origin", "*");
    	String sql = "select a.id , a.card_id ";
 		String andSql = " from card_discuss as a left join card as c on c.id = a.card_id left join users as card_users on card_users.id = c.user_id left join users u on u.id = a.user_id left join users as ta on a.buser_id = ta.id left join area ae on ae.code = u.area_id where a.is_discuss = 0 and a.card_id > 0 and a.create_time < "+ SystemClock.now()/1000L ;
 		// ta.is_true > 1 and
    	andSql += " and u.is_true = 1 and ( ( a.type= 1 and card_users.is_true > 1 ) or (ta.is_true > 1 and a.type= 2 and a.buser_id != a.user_id) )" ;
    	andSql += " order by a.id desc limit 1 ";
    	CardDiscuss discuss = CardDiscuss.dao.findFirst(sql +andSql);
    	Map<String,Object> result = Maps.newHashMap();
    	result.put("id",	discuss.get("id"));
    	result.put("card_id",	discuss.get("card_id"));
    	renderJson(result);
    }
    
    /**
     * 帖子列表 审核用
     */
 	@Before(AdminInterceptor.class)
    public void discuss_list() {
 		ArrayList<Area> areaList = CacheKit.get("constant", "arealist", new IDataLoader(){
		       public Object load() {
		           return Area.dao.getIProvince();
		}});
 		setAttr("area_list", areaList);
 	
 		String sql = "select a.*,u.nick_name,u.vip_end_time,u.is_gray,u.user_header,ae.name as area_name,u.sex,u.is_true,CASE u.sex  WHEN '1' THEN '男' WHEN '2' THEN '女' WHEN '3' THEN 'CD' WHEN '4' THEN 'FtM' WHEN '5' THEN 'MtF'  ELSE '其他' END as sex_name,case u.is_true when '2' then 'B类' when '3' then 'C类'  when '4' then 'D类' else 'A类' end as is_true_name ";
 		sql += ",c.user_id as card_user_id,c.content as card_content,FROM_UNIXTIME(a.create_time,'%Y-%m-%d %H:%i') as create_time_string , FROM_UNIXTIME(u.vip_end_time,'%Y-%m-%d') as vip_end_time_string  ";
 		
 		String andSql = " from card_discuss as a left join card as c on c.id = a.card_id left join users as card_users on card_users.id = c.user_id left join users u on u.id = a.user_id left join users as ta on a.buser_id = ta.id left join area ae on ae.code = u.area_id where a.is_discuss = 0 and a.card_id > 0 and c.create_time < "+ SystemClock.now()/1000L +" and a.create_time > " + (SystemClock.now()/1000L - 3 * 24*60*60L);
 		int type = 0;
 		int is_true = 1;
 		if(!StringUtil.empty(getPara("is_true"))) {
 			is_true = getParaToInt("is_true");
 			
 		}
 		//andSql += " and ta.is_true > 1 and u.is_true >1 and ( ( a.type= 1 and card_users.is_true > 1 ) or (a.type= 2 and a.buser_id != a.user_id) )" ;
 		if(StringUtil.empty(getPara("type"))) {
 			// and u.is_true = 1
        	andSql += " and a.type= 1 and card_users.is_true > 1 and u.is_true = " + is_true ;
        } else {
        	type = getParaToInt("type");
        	if (type == 0) {
        		//  and ta.is_true > 1    and u.is_true = 1 
        		andSql += " and a.type= 1 and card_users.is_true > 1 and u.is_true =  "  + is_true ;
        	} else if (type == 1) {
        		// and ta.is_true > 1 
        		andSql += " and ta.is_true > 1  and a.type= 2 and a.buser_id != a.user_id and u.is_true = "  + is_true ;
        	}
        }
        if(!StringUtil.empty(getPara("sex"))) {
        	andSql += " and u.sex = " + getPara("sex");
        }
        if(!StringUtil.empty(getPara("card_id"))) {
        	andSql += " and a.card_id = " + getPara("card_id");
        }
        if(!StringUtil.empty(getPara("id"))) {
        	andSql += " and a.id = " + getPara("id");
        }
        if(!StringUtil.empty(getPara("person"))) {
    		if (!"100".equalsIgnoreCase(getPara("person"))) {
    			ArrayList<Area> areaList2 = CacheKit.get("constant", "arealist_"+ getPara("person"), new IDataLoader(){
    			       public Object load() {
    			           return Area.dao.getIProvince(getPara("person"));
    			}});
    	 		setAttr("area_list", areaList2);
    	 		if (type == 0) {
    	 			andSql += StringUtil.getSQLForPerson3(getPara("person"));
    	 		} else if (type == 1) {
    	 			andSql += StringUtil.getSQLForPerson2(getPara("person"));
    	 		}
    		}
    	}
        if(!StringUtil.empty(getPara("content"))) {
        	andSql += " and (a.content like '%" + StringUtil.encode(getPara("content")).replace("%", "\\%")  +"%' or a.content like  '%" + getPara("content")+ "%')";
        }
        andSql += " order by a.id desc ";
        int page = 1;
        if(!StringUtil.empty(getPara("page"))) {
        	page = getParaToInt("page");
        } 
        Page<CardDiscuss> cardPage = CardDiscuss.dao.paginate(page, 15, sql,andSql);
        for(CardDiscuss one : cardPage.getList()) {
//        	one.set("content", StringUtil.decode(one.getStr("content")));
        	if (one.getUserId().intValue() == one.getBuserId().intValue()) {
        		int card_user_id = one.getInt("card_user_id");
        		one.setBuserId(Users.dao.findById(card_user_id).getIsTrue() == 1 ? 1 :0);
        		one.put("content", StringUtil.decode(one.getContent()));
    		} else {
    			Users users_temp = Users.dao.findById(one.getBuserId());
        		if (users_temp != null) {
        			one.put("content", "回复 "+ StringUtil.decode(users_temp.getNickName()) + ": "+ StringUtil.decode(one.getContent()));
        			one.setBuserId(users_temp.getIsTrue() == 1 ? 1 :0);
        		} else {
        			int card_user_id = one.getInt("card_user_id");
            		one.setBuserId(Users.dao.findById(card_user_id).getIsTrue() == 1 ? 1 :0);
        			one.put("content", StringUtil.decode(one.getContent()));
        		}
    		}
        }
        setAttr("page", cardPage);
        String person = getPara("person");
        if(StringUtil.empty(person)) {
            person = CookiesUtil.getName(getRequest(), "person");
        } else {
        	if ("100".equals(person)) {
        		CookiesUtil.add(getResponse(), "person", "0");
        	} else {
        		CookiesUtil.add(getResponse(), "person", person);
        	}
        }
        setAttr("person", person);
        setAttr("user_id", getPara("user_id"));
        setAttr("card_id", getPara("card_id"));
        setAttr("id", getPara("id"));
        setAttr("is_true", getPara("is_true"));
        setAttr("content", getPara("content"));
        setAttr("sex", getPara("sex"));
        setAttr("type", getPara("type"));
        setAttr("now", SystemClock.now()/1000);
        
        render("discuss_list.html");
    }

    /**
     * 帖子列表,只做审核用
     */
 	@Before(AdminInterceptor.class)
    public void fast_discuss_list() {
 		ArrayList<Area> areaList = CacheKit.get("constant", "arealist", new IDataLoader(){
		       public Object load() {
		           return Area.dao.getIProvince();
		}});
 		setAttr("area_list", areaList);
 	
 		String sql = "select a.id,a.user_id,a.card_id,a.buser_id,a.content,u.nick_name,u.vip_end_time,u.is_gray,u.user_header,ae.name as area_name,u.sex,u.is_true,CASE u.sex  WHEN '1' THEN '男' WHEN '2' THEN '女' WHEN '3' THEN 'CD' WHEN '4' THEN 'FtM' WHEN '5' THEN 'MtF'  ELSE '其他' END as sex_name,case u.is_true when '2' then 'B类' when '3' then 'C类'  when '4' then 'D类' else 'A类' end as is_true_name  ";
 		sql += ",FROM_UNIXTIME(a.create_time,'%Y-%m-%d %H:%i') as create_time_string , FROM_UNIXTIME(u.vip_end_time,'%Y-%m-%d') as vip_end_time_string  ";
 		String andSql = " from card_discuss as a left join users u on u.id = a.user_id left join area ae on ae.code = u.area_id where a.card_id > 0 and a.create_time < "+ SystemClock.now()/1000L ;
 		if(!StringUtil.empty(getPara("user_id"))) {
        	andSql += " and u.id = " + getPara("user_id");
        }
        if(!StringUtil.empty(getPara("is_true"))) {
        	int is_true = getParaToInt("is_true");
        	if (is_true < 100 ) {
        		andSql += " and u.is_true = " + getPara("is_true");
        	} else {
        		andSql += " and u.is_true = 1 and is_gray = 1 ";
        		
        	}
        }
        if(!StringUtil.empty(getPara("sex"))) {
        	andSql += " and u.sex = " + getPara("sex");
        }
        if(!StringUtil.empty(getPara("card_id"))) {
        	andSql += " and a.card_id = " + getPara("card_id");
        }
        if(!StringUtil.empty(getPara("id"))) {
        	andSql += " and a.id = " + getPara("id");
        }
        if(!StringUtil.empty(getPara("content"))) {
        	andSql += " and (a.content like '%" + StringUtil.encode(getPara("content")).replace("%", "\\%")  +"%' or a.content like  '%" + getPara("content")+ "%')";
        }
        andSql += " order by a.id desc ";
        int page = 1;
        if(!StringUtil.empty(getPara("page"))) {
        	page = getParaToInt("page");
        } 
        
        Page<CardDiscuss> cardPage = CardDiscuss.dao.paginate(page, 15, sql,andSql);
        for(CardDiscuss one : cardPage.getList()) {
        	if (one.getUserId().intValue() == one.getBuserId().intValue()) {
        		one.put("content", StringUtil.decode(one.getContent()));
    		} else {
    			Users users_temp = Users.dao.findById(one.getBuserId());
        		if (users_temp != null) {
        			one.put("content", "回复 "+ StringUtil.decode(users_temp.getNickName()) + ": "+ StringUtil.decode(one.getContent()));
        		} else {
        			one.put("content", StringUtil.decode(one.getContent()));
        		}
        		/*
        		else {
        			int card_user_id = one.getInt("card_user_id");
            		one.setBuserId(Users.dao.findById(card_user_id).getIsTrue() == 1 ? 1 :0);
        			one.put("content", StringUtil.decode(one.getContent()));
        		}*/
    		}
        	
        }
        setAttr("page", cardPage);
        setAttr("user_id", getPara("user_id"));
        setAttr("card_id", getPara("card_id"));
        setAttr("id", getPara("id"));
        setAttr("is_true", getPara("is_true"));
        setAttr("content", getPara("content"));
        setAttr("sex", getPara("sex"));
        setAttr("now", SystemClock.now()/1000);
        render("fast_discuss_list.html");
    }
 	
    //删除
    public void discuss_del(){
    	getResponse().setHeader("Access-Control-Allow-Origin", "*");
    	int id = getParaToInt("id");
    	Db.delete("delete from card_discuss where id = " + id);
        renderText("操作成功!");
    }
    
    public void discuss_del_select(){
    	String[] ids = getPara("ids").split(",");
 		for(String str :ids) {
 			Db.delete("delete from card_discuss where id = " + str);
 		}
 		renderText("操作成功!");
    }
    
    
     // 点赞
 	@Before(AdminInterceptor.class)
    public void give_like_select(){
 		String[] ids = getPara("ids").split(",");
 		for(String str :ids) {
 			int num = 3 + new Random().nextInt(11);
 			List<Users> usersList = Users.dao.find("SELECT t1.id FROM `users` AS t1 JOIN (SELECT ROUND(RAND() * (SELECT MAX(id) FROM `users`)) AS id) AS t2 WHERE t1.id >= t2.id and is_true > 1 ORDER BY t1.id ASC LIMIT " + num);
 			int id = Integer.valueOf(str);
 			Card card = Card.dao.findById(id);
 			for(int i = 0 ; i < usersList.size(); i++) {
 				Users u = usersList.get(i);
 				CardLike one = CardLike.dao.findFirst("select * from card_like where card_id = " + id +" and user_id = " + u.getId() +" order by id desc limit 1" );
 				if (one == null) {
 					one = new CardLike();
 					one.setCardId(id);
 					one.set("status", 1);
 					one.set("user_id", u.getId());
 					one.set("is_auth", 2);
 					one.setCreateTime(SystemClock.now()/1000L);
 		        	one.setUpdateTime(SystemClock.now()/1000L);
 					if (one.save()) {
 						giveABPoint(u.getId().intValue());
 						Db.update("update users set user_money = user_money + 6 where id = " +  u.getId());
 						Db.update("update card set sort_heat = sort_heat + 6,fabulous = fabulous + 1,views = views + 20,t_views = t_views + 20 where id = " +  id);
 						MessageUnreadNum.dao.addNum(MessageUnreadNum.MESSAGE_UNREAD_TYPE_LIKE, card.getUserId());
 					}
 				}
 	        } 
 		}
 	    renderText("操作成功!");
 	}
 	
 	@Before(AdminInterceptor.class)
    public void give_like_select2(){
 		String[] ids = getPara("ids").split(",");
 		for(String str :ids) {
 			List<Users> usersList = Users.dao.find("SELECT t1.id FROM `users` AS t1 JOIN (SELECT ROUND(RAND() * (SELECT MAX(id) FROM `users`)) AS id) AS t2 WHERE t1.id >= t2.id and is_true > 1  ORDER BY t1.id ASC LIMIT 1 ");
 			int id = Integer.valueOf(str);
 			Card card = Card.dao.findById(id);
 			for(int i = 0 ; i < usersList.size(); i++) {
 				Users u = usersList.get(i);
 				CardLike one = CardLike.dao.findFirst("select * from card_like where card_id = " + id +" and user_id = " + u.getId() +" order by id desc limit 1" );
 				if (one == null) {
 					one = new CardLike();
 					one.setCardId(id);
 					one.set("status", 1);
 					one.set("user_id", u.getId());
 					one.set("is_auth", 2);
 					one.setCreateTime(SystemClock.now()/1000L);
 		        	one.setUpdateTime(SystemClock.now()/1000L);
 					if (one.save()) {
 						giveABPoint(u.getId().intValue());
 						Db.update("update users set user_money = user_money + 6 where id = " +  u.getId());
 						Db.update("update card set sort_heat = sort_heat + 6,fabulous = fabulous + 1,views = views + 20,t_views = t_views + 20 where id = " +  id);
 						MessageUnreadNum.dao.addNum(MessageUnreadNum.MESSAGE_UNREAD_TYPE_LIKE, card.getUserId());
 					}
 				}
 	        } 
 		}
 	    renderText("操作成功!");
 	}
 	
 	@Before(AdminInterceptor.class)
    public void give_hot_select(){
 		String[] ids = getPara("ids").split(",");
 		for(String str :ids) {
 			int hot_value = 500 + new Random().nextInt(9501);
 			int id = Integer.valueOf(str);
 			Card card = Card.dao.findById(id);
 			Users user = Users.dao.findById(card.getUserId());
 			if (user != null && user.getIsTrue() > 1) {
 			// 帖子热度记录表
				CardHot hot = new CardHot();
				hot.setCardId(id);
				hot.setHotVal(hot_value);
				hot.setType(2);
				hot.save();
 				Db.update("update card set heat = heat + " + hot_value + ", t_heat = t_heat + " + hot_value+",sort_heat= sort_heat +4,tsort_heat= tsort_heat +4 where id =" + card.getId());
 				
 				Db.update("update users set hot_val = hot_val + " + hot_value/2 +" where id = " + card.getUserId());
 			}
 		}
 	    renderText("操作成功!");
 	}
 	
 	
 	@Before(AdminInterceptor.class)
    public void give_hot_select_2(){
 		String[] ids = getPara("ids").split(",");
 		for(String str :ids) {
 			int hot_value = 100 + new Random().nextInt(900);
 			int id = Integer.valueOf(str);
 			Card card = Card.dao.findById(id);
 			Users user = Users.dao.findById(card.getUserId());
 			if (user != null && user.getIsTrue()  > 1) {
 			// 帖子热度记录表
				CardHot hot = new CardHot();
				hot.setCardId(id);
				hot.setHotVal(hot_value);
				hot.setType(2);
				hot.save();
 				Db.update("update card set heat = heat + " + hot_value + ", t_heat = t_heat + " + hot_value+",sort_heat= sort_heat +4,tsort_heat= tsort_heat +4 where id =" + card.getId());
 				Db.update("update users set hot_val = hot_val + " + hot_value/2 +" where id = " + card.getUserId());
 			}
 		}
 	    renderText("操作成功!");
 	}
 	
 	@Before(AdminInterceptor.class)
    public void give_views_select(){
 		String[] ids = getPara("ids").split(",");
 		for(String str :ids) {
 			int views = 100 + new Random().nextInt(901);
 			Db.update("update card set views = views + " + views +" where id ="+ str);
 			
 		}
 	    renderText("操作成功!");
 	}
 	
 	
 	@Before(AdminInterceptor.class)
    public void giveDiscuss_select(){
 		String[] ids = getPara("ids").split(",");
 		String content = getPara("content");
		String area = getPara("area");
 		for(String str :ids) {
 			Card card = Card.dao.findById(str);
 			discuss(card,content,0,getPara("buser_id"),area);
 			
 		}
 	    renderText("操作成功!");
 	}
 	
 	// TODO
 	@Before(AdminInterceptor.class)
    public void giveDiscuss_select_temp(){
 		String[] ids = getPara("ids").split(",");
 		for(String str :ids) {
 			Card card = Card.dao.findById(str);
 			CardDiscuss temp_card = CardDiscuss.dao.findFirst("SELECT t1.content FROM `card_discuss` as t1 WHERE t1.type = "+ getPara("discuss_type") +" ORDER BY RAND() LIMIT 1;");
 			discuss(card,temp_card.getContent(),0,null,"0");
 			
 		}
 	    renderText("操作成功!");
 		
 	}
 	
 	/**
 	 * 忽略
 	 */
    public void discuss_ignore_select(){
		getResponse().setHeader("Access-Control-Allow-Origin", "*");
 		String[] ids = getPara("ids").split(",");
 		for(String str :ids) {
 			Db.update("update card_discuss set is_discuss = 1 where id = " + str);
 			
 		}
 	    renderText("操作成功!");
 	}
 	
	@Before(AdminInterceptor.class)
    public void giveDiscuss_one(){
 		String[] ids = getPara("ids").split(",");
 		String content = getPara("content");
		int user_id = getParaToInt("user_id");
 		for(String str :ids) {
 			Card card = Card.dao.findById(str);
 			CardDiscuss one = new CardDiscuss();
			one.setContent(StringUtil.encode(content) );
			one.setCardId(card.getId().intValue());
			one.setUserId(user_id);
			one.setBuserId(user_id);
			one.setCreateTime(SystemClock.now()/1000L);
        	one.setUpdateTime(SystemClock.now()/1000L);
        	one.set("type", 1);
			if (one.save()) {
				giveABPoint(user_id);
				Db.update("update card set discuss = discuss + 1,discuss_cnt = discuss_cnt + 1,views = views + 50,t_views = t_views + 50 where id = " + card.getId());
			}
 			
 		}
 	    renderText("操作成功!");
 	}
 	
 	
 	@Before(AdminInterceptor.class)
    public void house(){
    	ArrayList<Social> socialList = CacheKit.get("constant", "sociallist", new IDataLoader(){
		       public Object load() {
		           return Social.dao.getAll();
		}});
    	ArrayList<Area> areaList = CacheKit.get("constant", "arealist", new IDataLoader(){
		       public Object load() {
		           return Area.dao.getIProvince();
		}});
    	setAttr("social_list", socialList);
    	setAttr("area_list", areaList);
    	
    	String sql = "select a.* ,a.is_show ,u.nick_name,u.user_mobile,u.is_gray,u.id as user_id,s.title as social_title,u.vip_end_time,ae.name as area_name,u.sex,u.is_true,CASE u.sex  WHEN '1' THEN '男' WHEN '2' THEN '女' WHEN '3' THEN 'CD' WHEN '4' THEN 'FtM' WHEN '5' THEN 'MtF'  ELSE '其他' END as sex_name,case u.is_true when '2' then 'B类' when '3' then 'C类'  when '4' then 'D类' else 'A类' end as is_true_name ";
    	sql += ",case a.card_type when '1' then '有图无链接' else '有链接无图' end as card_type_name , FROM_UNIXTIME(a.create_time,'%Y-%m-%d %H:%i') as create_time_string , FROM_UNIXTIME(u.vip_end_time,'%Y-%m-%d') as vip_end_time_string  ";
    	String andSql = " from card as a left join users u on u.id = a.user_id left join social s on  s.id = a.tags_id left join area ae on ae.code = u.area_id where a.create_time = 1893427200 " ;
    	
    	if(!StringUtil.empty(getPara("sex"))) {
         	andSql += " and u.sex = " + getPara("sex");
        } else {
        	 andSql += " and u.sex = 1 " ; 
        }
    	if(!StringUtil.empty(getPara("user_id"))) {
        	andSql += " and u.id = " + getPara("user_id");
        }
    	
        if(!StringUtil.empty(getPara("content"))) {
        	andSql += " and a.content like '%" + StringUtil.encode(getPara("content")).replace("%", "\\%")  +"%' ";
        }
        if(!StringUtil.empty(getPara("card_id"))) {
        	andSql += " and a.id = " + getPara("card_id");
        }
        
        if(!StringUtil.empty(getPara("sex"))) {
        	andSql += " and u.sex = " + getPara("sex");
        }
        if(!StringUtil.empty(getPara("area"))) {
        	andSql += " and ae.code = " + getPara("area");
        }
        int page = 1;
        if(!StringUtil.empty(getPara("page"))) {
        	page = getParaToInt("page");
        } 
        
        Page<Card> cardPage = Card.dao.paginate(page, 15, sql,andSql);
        for(Card c : cardPage.getList()) {
        	c.set("content", StringUtil.decode(c.getStr("content")));
        }
        setAttr("page", cardPage);
        setAttr("user_mobile", getPara("user_mobile"));
        setAttr("user_id", getPara("user_id"));
        setAttr("social", getPara("social"));
        setAttr("nick_name", getPara("nick_name"));
        setAttr("card_id", getPara("card_id"));
        setAttr("sex", getPara("sex"));
        setAttr("area", getPara("area"));
        setAttr("content", getPara("content"));
        render("house"+ (getPara("sex") == null ? 1 : getPara("sex"))+".html");
 	}
 	
 	public void quick_insert() {
 		String images = getPara("images");
		String[] arr_images = null;
		if (!StringUtil.empty(images)) {
			if (images.endsWith(",")) {
				images = images.substring(0, images.length() -1);
			}
			arr_images = images.split(",");
		}
		int user_id = 0;
		
		if (StringUtil.empty(getPara("sex")) ) {
			// 随机男
			/*
			NavyUsers users = NavyUsers.dao.findFirst("select user_id from navy_users where admin_user_id = 44 and user_id > 451099 order by rand() limit 1 ");
			user_id = users.getUserId();
			*/
			Users users = Users.dao.findFirst("select u.id from users as u LEFT JOIN users_info as i on i.user_id = u.id where u.is_true = 3 and u.sex =1 and i.lat > 0 and i.lng > 0 order by rand() limit 1 ");
			user_id = users.getId().intValue();
		} else {
			Users users = Users.dao.findFirst("select u.id from users as u LEFT JOIN users_info as i on i.user_id = u.id where u.is_true = 3 and u.sex =2 and i.lat > 0 and i.lng > 0 order by rand() limit 1 ");
			user_id = users.getId().intValue();
		}
		Card one = new Card();
		one.setTagsId(1);
		one.setUserId(user_id);
		one.setCreateTime(SystemClock.FUTURE_TIME);
    	one.setUpdateTime(SystemClock.FUTURE_TIME);
    	one.setContent(getPara("content"));
		one.setImgCheck(1);
		one.setIsShow(1);
		one.setIsCheck(1);
		one.setImages(images);
		if (StringUtil.empty(getPara("sex")) ) {
			one.setViews(1 + new Random().nextInt(10));
		} else {
			one.setViews(30 + new Random().nextInt(100));
		}
		if (one.save()) {
			if (arr_images != null) {
				for(String t :arr_images) {
					CardImg img = new CardImg();
					img.setCardId(one.getId().intValue());
					img.setImageUrl(t);
					img.setCreateTime(SystemClock.now()/1000L);
					img.setUpdateTime(SystemClock.now()/1000L);
					img.setImgCheck(1);
					img.save();
				}
			}
		}
		renderText("操作成功!");
 	}
}
